package com.baijiayun.liveuibase.widgets.dialog;

import android.content.Context;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.ColorInt;

import com.baijiayun.livecore.context.LPConstants;
import com.baijiayun.livecore.models.LPAwardUserInfo;
import com.baijiayun.livecore.models.LPInteractionAwardModel;
import com.baijiayun.livecore.models.imodels.IUserModel;
import com.baijiayun.livecore.models.launch.LPAwardConfig;
import com.baijiayun.liveuibase.R;
import com.baijiayun.liveuibase.base.RouterListener;
import com.baijiayun.liveuibase.utils.ThemeDataUtil;
import com.baijiayun.liveuibase.widgets.popupwindow.BaseAutoArrangePopupWindow;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;

public class AwardPopupWindow extends BaseAutoArrangePopupWindow {
    private final IOnItemClickListener onItemClickListener;
    private HashMap<String, TextView> tvAwardCounts;
    private IUserModel userModel;
    private final CompositeDisposable compositeDisposable = new CompositeDisposable();
    private LPAwardUserInfo awardUserInfo;
    private long lastDismissTime = -1;
    private final RelativeLayout contentView;
    private boolean isGalleryLayout;
    private final RouterListener routerListener;

    public AwardPopupWindow(Context context, IOnItemClickListener onItemClickListener) {
        this(context, null, onItemClickListener);
    }

    public AwardPopupWindow(Context context, IUserModel userModel,
                            IOnItemClickListener onItemClickListener) {
        super(context);
        this.userModel = userModel;
        if (context instanceof RouterListener) {
            this.routerListener = (RouterListener) context;
        } else {
            throw new RuntimeException("context is not extends RouterListener");
        }
        this.onItemClickListener = onItemClickListener;
        contentView = new RelativeLayout(context);
        initCustomOffset(-8, -4);
        createView(contentView, false);
        setDirectionMode(HORIZONTAL);
        setOnDismissListener(() -> {
            lastDismissTime = System.currentTimeMillis();
            contentView.removeAllViews();
            unSubscribe();
        });
    }

    public void setUserModel(IUserModel userModel) {
        this.userModel = userModel;
    }

    private void subscribe() {
        if (routerListener.getLiveRoom() == null) {
            return;
        }
        isGalleryLayout = routerListener.getLiveRoom().getCurrentRoomLayout() == LPConstants.RoomLayoutMode.GALLERY;
        updateAwardCount(routerListener.getLiveRoom().getAwardValue());
        compositeDisposable.add(routerListener.getLiveRoom().getObservableOfRoomLayoutSwitch()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(mode -> dismiss()));
        compositeDisposable.add(routerListener.getLiveRoom().getObservableOfAward()
                .ofType(LPInteractionAwardModel.class)
                .filter(lpInteractionAwardModel -> lpInteractionAwardModel.isFromCache
                        || lpInteractionAwardModel.value.to.equals(userModel.getNumber())
                        || lpInteractionAwardModel.value.to.equals("-1"))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(awardModel -> {
                    updateAwardCount(awardModel);

                    if (awardModel.isFromCache) {
                        // 缓存全部更新
                        for (Map.Entry<String, TextView> entry : tvAwardCounts.entrySet()) {
                            entry.getValue().setText(getCountFromModel(entry.getKey()));
                        }
                    } else {
                        // 奖励，单个更新
                        TextView textView = tvAwardCounts.get(awardModel.value.awardType);
                        if (textView != null) {
                            textView.setText(getCountFromModel(awardModel.value.awardType));
                        }
                    }
                })
        );
    }

    private void unSubscribe() {
        compositeDisposable.clear();
    }

    private void generateContentView(RelativeLayout contentView) {
        if (routerListener.getLiveRoom() == null) {
            return;
        }
        contentView.setBackground(ThemeDataUtil.getCommonWindowBgWithBorder(context));
        tvAwardCounts = new HashMap<>();

        int itemMargin = context.getResources().getDimensionPixelOffset(R.dimen.bjy_base_award_popup_window_item_margin);
        int iconSize = context.getResources().getDimensionPixelSize(R.dimen.bjy_base_award_popup_window_icon_size);
        int tvWidth = context.getResources().getDimensionPixelOffset(R.dimen.bjy_base_award_popup_window_award_count_tv_width);
        @ColorInt int textColor = ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_window_main_text_color);

        LPAwardConfig[] awardConfigs = routerListener.getLiveRoom().getAwardConfigs();
        RelativeLayout preLineItem = null;
        for (LPAwardConfig awardConfig : awardConfigs) {
            if (awardConfig.isEnable == 1) {
                RelativeLayout item = new RelativeLayout(context);

                // region 设置 icon
                ImageView imageView = new ImageView(context);
                imageView.setImageDrawable(LPConstants.getAwardTypeDrawable(awardConfig.key, LPConstants.AwardTypeDrawable.Logo));
                imageView.setId(View.generateViewId());
                item.addView(imageView, new RelativeLayout.LayoutParams(iconSize, iconSize));
                // endregion

                // region 生成点赞数 视图 并保存
                TextView textView = new TextView(context);
                RelativeLayout.LayoutParams tvParams = new RelativeLayout.LayoutParams(
                        tvWidth, iconSize);
                tvParams.addRule(RelativeLayout.CENTER_VERTICAL);
                tvParams.addRule(RelativeLayout.END_OF, imageView.getId());
                textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                        context.getResources().getDimension(R.dimen.bjy_base_award_popup_window_text_size));
                textView.setTextColor(textColor);
                textView.setText(getCountFromModel(awardConfig.key));
                textView.setLayoutParams(tvParams);
                textView.setGravity(Gravity.CENTER_VERTICAL);
                item.addView(textView, tvParams);

                tvAwardCounts.put(awardConfig.key, textView);
                // endregion

                RelativeLayout.LayoutParams itemParams = new RelativeLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                item.setId(View.generateViewId());
                if (preLineItem != null) {
                    itemParams.addRule(RelativeLayout.BELOW, preLineItem.getId());
                }
                preLineItem = item;
                itemParams.setMargins(itemMargin, itemMargin, itemMargin, itemMargin);

                // region item 点击事件
                item.setOnClickListener(v -> onItemClick(awardConfig.key));
                // endregion

                contentView.addView(item, itemParams);
            }
        }
    }

    private boolean canAward(IUserModel user) {
        if (routerListener.getLiveRoom() == null || !routerListener.getLiveRoom().isClassStarted()) {
            return false;
        }
        //大班课
        if (routerListener.getLiveRoom().getRoomType() == LPConstants.LPRoomType.Multi && routerListener.getLiveRoom().isGroupClass()) {
            if (routerListener.getLiveRoom().isTeacherOrAssistant()) {
                return true;
            } else if (routerListener.getLiveRoom().isGroupTeacherOrAssistant()) {
                if (user == null) {
                    return false;
                }
                return routerListener.getLiveRoom().getCurrentUser().getGroup() == user.getGroup();
            }
            return false;
        } else {
            return routerListener.getLiveRoom().isTeacherOrAssistant();
        }
    }

    /**
     * item 点赞点击事件
     */
    private void onItemClick(String key) {
        if (routerListener.getLiveRoom() == null) {
            dismiss();
            return;
        }
        if (!canAward(this.userModel)) {
            dismiss();
            return;
        }
        if (onItemClickListener != null) {
            onItemClickListener.onItemClick(userModel, key);
        }
        dismiss();
    }

    private void updateAwardCount(LPInteractionAwardModel awardModel) {
        if (awardModel == null) {
            return;
        }
        this.awardUserInfo = awardModel.value.recordAwardAll.recordAward.get(userModel.getNumber());
    }

    private String getCountFromModel(String key) {
        if (awardUserInfo != null && awardUserInfo.typeCount != null) {
            Integer value = awardUserInfo.typeCount.get(key);
            return String.valueOf(value == null ? 0 : value);
        }
        return "0";
    }

    @Override
    protected void initViewDataHashMap() {
        // do nothing
    }

    @Override
    public void show(View anchor) {
        if (userModel == null) {
            return;
        }
        if (System.currentTimeMillis() - lastDismissTime > 200) {
            generateContentView(contentView);
            subscribe();
            showWithViewOfDirection(anchor, isGalleryLayout ? LEFT_TOP : LEFT_BOTTOM);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        compositeDisposable.clear();
    }

    public interface IOnItemClickListener {
        void onItemClick(IUserModel userModel, String awardKey);
    }
}
